/**
 * Created by guomin on 2017/5/4.
 */
var Promise=require('bluebird');
var sqlWishes=require('../dao/wishesMapping');
var sqlUsers=require('../dao/usersMapping');
var sqlLike=require('../dao/likeMapping');
var sqlArea=require('../dao/areaMapping');
var sqlLetter=require('../dao/letterMapping');

var checkParams=require('../common/checkParams');

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

var getData={
    getWishes:function(connection,params){
        return new Promise(function(resolve,reject){
            var pageN=parseInt(params.pageNow);
            var pageS=parseInt(params.pageSize);
            console.log("pageNow",pageN);
            console.log("pageSize",pageS);
            if(pageN<=0||pageS<=0){
                reject(102);
            }else{
                connection.query(sqlWishes.getWishes,[(pageN-1)*pageS,pageS]).then(function(data){
                    if(data.length>0){
                        for(var i=0;i<data.length;i++){
                            if(data[i].thumbnail!=null){
                                data[i].thumbnail="http://wxy.gongyi.k618.cn"+data[i].thumbnail;
                            }
                        }
                        console.log("wishesList",data);
                        var result={"pageNow":pageN,"result":data};
                        resolve(result);
                    }else{
                        resolve({"pageNow":pageN,"result":data});
                    }
                }).catch(function(error){
                    reject(error);
                });
            }
        });
    },
  getClaimWishes:function(connection,params){
    return  new Promise(function(resolve,reject){
      var pageN = parseInt(params.pageNow);
      var pageS = parseInt(params.pageSize);
      var status = parseInt(params.status);
      if(pageN<=0||pageS<=0||status<0){
        reject(102);
      }else{
        if(status === 1){
          connection.query(sqlWishes.getClaimedWishes,[(pageN-1)*pageS,pageS]).then(function(data){
            if(data.length>0){
              for(var i=0;i<data.length;i++){
                if(data[i].thumbnail!=null){
                  data[i].thumbnail="http://wxy.gongyi.k618.cn"+data[i].thumbnail;
                }
              }
              console.log("wishesList",data);
              var result={"pageNow":pageN,"result":data};
              resolve(result);
            }else{
              resolve({"pageNow":pageN,"result":data});
            }
          }).catch(function(error){
            reject(error);
          });
        }else if(status === 0){
          connection.query(sqlWishes.getUnClaimedWished,[(pageN-1)*pageS,pageS]).then(function(data){
            if(data.length>0){
              for(var i=0;i<data.length;i++){
                if(data[i].thumbnail!=null){
                  data[i].thumbnail="http://wxy.gongyi.k618.cn"+data[i].thumbnail;
                }
              }
              console.log("wishesList",data);
              var result={"pageNow":pageN,"result":data};
              resolve(result);
            }else{
              resolve({"pageNow":pageN,"result":data});
            }
          }).catch(function(error){
            reject(error);
          });
        }else{
          reject(102);
        }
      }
    });
  },
    getWishDetail:function(connection,params){
        return new Promise(function(resolve,reject){
            var wid=params.wid;
            var uid=params.uid;
            console.log("wishID",wid);
            console.log("claimId",uid);
            connection.query(sqlWishes.getWishDetailByID,wid).then(function(data){
                if(data.length>0){
                    var result=data[0];
                    console.log(result);
                    result.thumbnail="http://wxy.gongyi.k618.cn"+result.thumbnail;
                    var str=result.familydesc;
                    if(str!=null){
                        var strResult=str.replace(/\/ueditor\/php/g,"http://wxy.gongyi.k618.cn/ueditor/php");
                        result.familydesc=strResult;
                    }
                    console.log("wishDetail",result);
                    if(result.claimantid!=uid||result.status==0){
                        console.log("无人认领或认领人ID不对");
                        delete result["claimantid"];
                        delete result["province"];
                        delete result["city"];
                        delete result["county"];
                        delete result["takename"];
                        delete result["takemobile"];
                        delete result["address"];
                        resolve(result);
                    }else if(result.status==1){
                        console.log("心愿认领审核中");
                        delete result["province"];
                        delete result["city"];
                        delete result["county"];
                        delete result["takename"];
                        delete result["takemobile"];
                        delete result["address"];
                        resolve(result);
                    }else{
                        console.log("_________________");
                        getAreaName(connection,result).then(function(detailAddress){
                            result.address=detailAddress;
                            delete result["province"];
                            delete result["city"];
                            delete result["county"];
                            resolve(result);
                        }).catch(function(err){
                            if(err)
                                reject(err);
                        });
                    }
                }else{
                    reject(205)
                }

            }).catch(function(error){
                reject(error);
            });
        });
    },
    likeWish:function(connection,params){
        return new Promise(function(resolve,reject){
            console.log(params);
            var wid=params.wid;
            var code=params.code;
            connection.query(sqlWishes.queryWishById,wid).then(function(result){
                if(result.length>0){
                    connection.query(sqlLike.queryByCodeAndWid,[wid,code]).then(function(result){
                        if(result.length==0){
                            connection.query(sqlLike.insert,[wid,code]).then(function(){
                                return connection.query(sqlWishes.updateLike,wid);
                            }).then(function(){
                                resolve(true);
                            }).catch(function(error){
                                reject(error);
                            });
                        }else{
                            reject(202);
                        }
                    }).catch(function(error){
                        reject(error);
                    });
                }else{
                    reject(205);
                }
            }).catch(function(error){
                reject(error);
            })

        })
    },
    //获取已认领过心愿人的联系地址、精锐学员号等信息
    getUserInfo:function(connection,uid){
        return new Promise(function(resolve,reject){
           connection.query(sqlUsers.queryUserInfoByUid,uid).then(function(result){
               if(result.length>0){
                   resolve(result[0]);
               }else{
                   reject(204);
               }
           }).catch(function(error){
               reject(error);
           });
        });
    },
    //提交认领申请
    claimWish:function(connection,params){
        return new Promise(function(resolve,reject){
            console.log("claimwish_________",params);
            isWishRight(connection,params.wid).then(function(){
                return isUserExist(connection,params);
            }).then(function(result){
                if(result=="notexist"){
                    return insertUser(connection,params);
                }else{
                    return updateUser(connection,params);
                }
            }).then(function(result){
                params.uid=result;
                return updateWish(connection,params);
            }).then(function(){
                return insertUserWish(connection,params);
            }).then(function(result){
                resolve(result);
            }).catch(function(error){
                reject(error);
            });
        });
    },
    //假登录，若用户存在返回UID，若不存在创建新用户，返回UID
    login:function(connection,params){
        return new Promise(function(resolve,reject){
            console.log("login params __________",params);
            isUserExist(connection,params).then(function(result){
                if(result=="notexist"){
                    return insertUser(connection,params);
                }else{
                    return result;
                }
            }).then(function(result){
                console.log("login uid",result);
                resolve(result);
            }).catch(function(error){
                reject(error);
            })
        });
    },
    getClaimedWishList:function(connection,params){
        return new Promise(function(resolve,reject){
            var uid=params.uid;
            connection.query(sqlWishes.getClaimedWishList,[uid]).then(function(data){
                return Promise.all(data.map(function(result){
                    return getAreaName(connection,result).then(function(detailAddress){
                        if(result.thumbnail!=null){
                            result.thumbnail="http://wxy.gongyi.k618.cn"+result.thumbnail;
                        }
                        if(result.status==2){
                            result.address=detailAddress;
                            delete result["province"];
                            delete result["city"];
                            delete result["county"];
                            return(result);
                        }else{
                            delete result["province"];
                            delete result["city"];
                            delete result["county"];
                            delete result["takename"];
                            delete result["takemobile"];
                            delete result["address"];
                            return(result);
                        }
                    }).catch(function(err){
                        if(err)
                            reject(err);
                    });
                }));
            }).then(function(data){
                console.log(data);
                resolve(data);
            }).catch(function(error){
                reject(error);
            });
        });
    },
    getLetterList:function(connection,params){
        return new Promise(function(resolve,reject){
            var pageN=parseInt(params.pageNow);
            var pageS=parseInt(params.pageSize);
            connection.query(sqlLetter.getLetterList,[(pageN-1)*pageS,pageS]).then(function(data){
                if(data.length>0){
                    for(var i=0;i<data.length;i++){
                        if(data[i].thumbnail!=null){
                            data[i].thumbnail="http://wxy.gongyi.k618.cn"+data[i].thumbnail;
                        }
                    }
                    console.log("letterList",data);
                    var result={"pageNow":pageN,"result":data};
                    resolve(result);
                }else{
                    resolve({"pageNow":pageN,"result":data});
                }
            }).catch(function(error){
                reject(error);
            });
        })
    },
    getLetterDetail:function(connection,params){
        return new Promise(function(resolve,reject){
           var id=params.id;
           connection.query(sqlLetter.getLetterDetailByID,[id]).then(function(data){
               if(data.length>0){
                   var result=data[0];
                   result.thumbnail="http://wxy.gongyi.k618.cn"+result.thumbnail;
                   var str=result.content;
                   if(str!=null){
                       var strResult=str.replace(/\/ueditor\/php/g,"http://wxy.gongyi.k618.cn/ueditor/php");
                       result.content=strResult;
                   }
                   console.log(result);
                   resolve(result);
               }else{
                   reject(207);
               }
           }).catch(function(error){
               reject(error);
           });
        });
    }
};

//验证心愿是否存在，若存在状态是否为等待认领
function isWishRight(connection,wid){
    return new Promise(function(resolve,reject){
        connection.query(sqlWishes.queryWishById,wid).then(function(result){
            console.log("checkWishRight_______",result);
            if(result.length>0){
                var data=result[0];
                if(data.status!=0){
                    reject(206);
                }else{
                    resolve(true);
                }
            }else{
                reject(205);
            }
        });
    });
}

//验证用户是否已存在，若存在返回UID，不存在返回"notexist"
function isUserExist(connection,params){
    return new Promise(function(resolve,reject){
        console.log("isUserExist_______",params);
        connection.query(sqlUsers.queryUidByMobile,params.mobile).then(function(result){
            console.log(result);
            if(result.length>0){
                connection.query(sqlWishes.getClaimedWishCount,result[0].id).then(function(count){
                    console.log("count____________",count);
                    console.log("count.count____________",count[0].count);
                    if(count[0].count>=2){
                        reject({"code":207,"uid":result[0].id});
                    }else{
                        resolve(result[0].id);
                    }
                }).catch(function(err){
                    reject(err);
                });
            }else{
                resolve("notexist");
            }
        }).catch(function(err){
            reject(err);
        });
    });
}
//插入新的认领人
function insertUser(connection,params){
    return new Promise(function(resolve,reject){
        connection.query(sqlUsers.insertClaimant,[params.mobile,params.name,params.address]).then(function(result){
            // console.log("insert user result",result);
            resolve(result.insertId);
        }).catch(function(err){
            reject(err);
        });
    });
}

//更新已有认领人信息
function updateUser(connection,params){
    return new Promise(function(resolve,reject){
        var uid;
        connection.query(sqlUsers.queryUidByMobile,params.mobile).then(function(result){
            uid=result[0].id;
            return connection.query(sqlUsers.updateClaimant,[params.address,uid]);
        }).then(function(){
            // console.log(uid);
            resolve(uid);
        }).catch(function(err){
            reject(err);
        });
    });
}

//更新心愿认领信息
function updateWish(connection,params){
    return new Promise(function(resolve,reject){
        var date=new Date();
        var queryParams=[params.uid,date.Format('yyyy-MM-dd hh:mm:ss'),params.wid];
        connection.query(sqlWishes.updateClaimant,queryParams).then(function(){
            resolve(true);
        }).catch(function(err){
            reject(err);
        });
    });
}

//认领人心愿认领关系
function insertUserWish(connection,params){
    return new Promise(function(resolve,reject){
        connection.query(sqlUsers.insertUserWish,[params.uid,params.wid]).then(function(){
            resolve(params.uid);
        }).catch(function(err){
            reject(err);
        });
    });
}

//获取省市县名称
function getAreaName(connection,params){
    return new Promise(function(resolve,reject){
        var pid=params.province;
        var cityid=params.city;
        var countyid=params.county;
        var addstr=params.address;
        var address="";
        connection.query(sqlArea.getNameByID,pid).then(function(result){
            address+=result[0].name;
            return connection.query(sqlArea.getNameByID,cityid);
        }).then(function(result){
            address+=result[0].name;
            return connection.query(sqlArea.getNameByID,countyid);
        }).then(function(result){
            address=address+result[0].name+addstr;
            console.log("getAreaName_____________________"+address);
            resolve(address);
        }).catch(function(err){
            reject(err);
        });
    })
}

exports=module.exports=getData;